using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using ExamServer.Entities;
using ExamServer.Models;
using ExamServer.Service;

namespace ExamServer.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class QuestionTypeController : ControllerBase
    {
        public QuestionTypeController(IRepositoryWrapper wrapper, IMapper mapper)
        {
            Wrapper = wrapper;
            Mapper = mapper;
        }

        public IRepositoryWrapper Wrapper { get; }
        public IMapper Mapper { get; }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<QuestionTypeModel>>> Get()
        {
            var list = Mapper.Map<IEnumerable<QuestionTypeModel>>(await Wrapper.QuestionTypes.GetAllAsync());
            return Ok(list);
        }
        [HttpGet("{id}")]
        public async Task<ActionResult<QuestionTypeModel>> GetModel(int id)
        {
            var entity = await Wrapper.QuestionTypes.GetByIdAsync(id);
            if (entity == null)
            {
                return NotFound();
            }
            var model = Mapper.Map<QuestionTypeModel>(entity);
            return Ok(model);
        }

        [HttpPost]
        public async Task<ActionResult<QuestionTypeModel>> Insert(QuestionTypeModel model)
        {
            var entity = new QuestionType();
            entity.TypeName = model.TypeName;
            entity.Remark = model.Remark;
            entity.TypeState = (StateEnum)Enum.Parse(typeof(StateEnum), model.StateDisplay);
            Wrapper.QuestionTypes.Creatre(entity);
            var bl = await Wrapper.QuestionTypes.SaveAsync();
            if (bl)
            {
                return CreatedAtRoute("", model);
            }
            else
            {
                return NotFound();
            }
        }
        [HttpPut]
        public async Task<ActionResult<QuestionTypeModel>> Update(QuestionTypeModel model)
        {
            var entity = new QuestionType();
            entity.Id = model.Id;
            entity.Remark = model.Remark;
            entity.TypeName = model.TypeName;
            entity.TypeState = (StateEnum)Enum.Parse(typeof(StateEnum), model.StateDisplay);
            Wrapper.QuestionTypes.Update(entity);
            var bl = await Wrapper.QuestionTypes.SaveAsync();
            if (bl)
            {
                return RedirectToRoute("", model);
            }
            else
            {
                return NotFound();
            }
        }
    }
}